package user.zc.config.system.config;


import lombok.Getter;
import user.zc.config.MapConfig;
import user.zc.config.ValueType;
import user.zc.config.value.Key;

import java.io.*;
import java.util.Map;

/**
 * @author zhouchuang
 * @date 2023/8/9 17:54
 */
@Getter
public abstract class SystemConfig<T extends Key> extends MapConfig<T> {
    protected static final String EXT = ".conf";

    public SystemConfig(ValueType type)throws Exception {
        super(type);
        loadConfig(this.getClass().getSimpleName());
        //需要调用复制方法，复制配置类过去
        copyFile(this.getClass().getSimpleName());
    }

    @Override
    public File getFile(String fileName){
        File file =  new File(System.getProperty("user.home")+File.separator + FOLD+File.separator+"system"+File.separator+fileName+EXT);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        return file;
    }


    @Override
    protected BufferedReader getConfBufferedReader(String fileName)throws Exception{
        //先判断有么有文件，如果没有就从资源里面读取
        File file  = null;
        if((file = getFile(fileName)).exists()){
            return new BufferedReader(new FileReader(file));
        }else{
            return new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(fileName+EXT)));
        }
    }

    //重载方法，对于配置文件来说，没有用户概念，可以共用
    public  void saveOrUpdate( Map<String,T> map)throws Exception{
        saveOrUpdate(this.getClass().getSimpleName(),map);
    }

    @Override
    public void copyFile(String fileName)throws Exception{
        if( !getFile(fileName).exists()){
            saveOrUpdate(fileName,getData());
        }
    }
}
